package com.darren.framework.entity;

import com.darren.framework.shiro.ShiroUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.time.Instant;

@Component
@Transactional
public class DataEntityListener {

    private Logger logger = LogManager.getLogger(getClass());

    @PrePersist
    public void prePersist(BaseEntity baseEntity)
            throws IllegalArgumentException, IllegalAccessException {
        Timestamp now = Timestamp.from(Instant.now());
        baseEntity.setCreateTime(now);
        Long userId = ShiroUtil.getUserId();
        baseEntity.setCreateBy(userId);
        logger.info("before save" + userId);
    }

    @PostPersist
    public void postPersist(BaseEntity baseEntity)
            throws IllegalArgumentException, IllegalAccessException {
        Long userId = ShiroUtil.getUserId();
        logger.info("after save" + userId);
    }

    @PreUpdate
    public void preUpdate(BaseEntity baseEntity)
            throws IllegalArgumentException, IllegalAccessException {
        Timestamp now = Timestamp.from(Instant.now());
        baseEntity.setUpdateTime(now);
        Long userId = ShiroUtil.getUserId();
        logger.info("before update" + userId);
    }

    @PostUpdate
    public void postUpdate(BaseEntity baseEntity)
            throws IllegalArgumentException, IllegalAccessException {
        Long userId = ShiroUtil.getUserId();
        logger.info("after update" + userId);
    }

    @PreRemove
    public void preRemove(BaseEntity baseEntity) {
        Long userId = ShiroUtil.getUserId();
        logger.info("before delete" + userId);

    }

    @PostRemove
    public void postRemove(BaseEntity baseEntity) {
        Long userId = ShiroUtil.getUserId();
        logger.info("after delete" + userId);
    }

}
